<?php
/**
 * Created by PhpStorm.
 * User: admin
 * Date: 2022-11-17
 * Time: 19:30
 */

namespace App\server\dtk;


use App\model\WechatApp;
use GuzzleHttp\Client;
use support\exception\MethodNotAllowed;
use support\exception\ModelError;

class DtkClient
{
    private $response;
    public function __construct($baseUrl,$data,$appId=6)
    {
        $config=WechatApp::where('id',$appId)->find();
        if(!$config){
            throw new ModelError('查询不到对应APP');
        }
        $appSecret=$config['secret'];
        $data['appKey']=$config['app_id'];
        $data['sign'] =self::makeSign($data,$appSecret);
        $url=self::buildUrl($baseUrl,$data);
        $client=new Client();
        $response = $client->get($url);
        if($response->getStatusCode()!==200){
            throw new MethodNotAllowed('对外请求错误');
        }
       $this->response=$response->getBody()->getContents();
    }

    public function getBody(){
        return $this->response;
    }
    public static function makeSign($data, $appSecret)
    {
        ksort($data);
        $str = '';
        foreach ($data as $k => $v) {

            $str .= '&' . $k . '=' . $v;
        }
        $str = trim($str, '&');
        $sign = strtoupper(md5($str . '&key=' . $appSecret));
        return $sign;
    }

    public static function buildUrl($baseUrl,$data  )
    {
        return $baseUrl .'?'. http_build_query($data);
    }

}